package com.wootion.cims.module.systemsetting.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wootion.cims.dao.*;
import com.wootion.cims.general.enumtype.Security;
import com.wootion.cims.general.utils.GetIp;
import com.wootion.cims.general.utils.RedisUtil;
import com.wootion.cims.module.systemsetting.community.model.SysCommunity;
import com.wootion.cims.module.systemsetting.log.model.SysLog;
import com.wootion.cims.module.systemsetting.role.model.SysRole;
import com.wootion.cims.module.systemsetting.system.model.SysConfiguration;
import com.wootion.cims.module.systemsetting.user.model.SysUserCommunity;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.module.systemsetting.user.service.SysUserService;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<UserDao, User> implements SysUserService {

    @Autowired
    RedisUtil redisUtil;

    @Autowired(required = false)
    UserDao sysUserDao;

    @Autowired(required = false)
    SysUserRoleDao sysUserRoleDao;

    @Autowired(required = false)
    SysUserCommunityDao sysUserCommunityDao;

    @Autowired(required = false)
    SysRoleDao sysRoleDao;

    @Autowired(required = false)
    SysRoleMenuDao sysRoleMenuDao;
    
    @Autowired(required = false)
    SysMenuDao sysMenuDao;

    @Autowired(required = false)
    SysCommunityDao sysCommunityDao;
    
    @Autowired(required = false)
    SysPlotDao sysPlotDao;

    @Autowired(required = false)
    SysLogDao sysLogDao;

    @Autowired(required = false)
    SysConfigurationDao sysConfigurationDao;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insert(JSONObject sysUser) {
        User user = JSONObject.parseObject(sysUser.toJSONString(), User.class);
//        用户名,手机号验重
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
//        queryWrapper.eq("enabled",true);
        User user2 = sysUserDao.selectOne(queryWrapper);
        if (Optional.ofNullable(user2).isPresent()) {
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("用户名已存在").build();
        }

        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("tel", user.getTel());
//        queryWrapper.eq("enabled",true);
        User user3 = sysUserDao.selectOne(queryWrapper2);
        if (Optional.ofNullable(user3).isPresent()) {
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("手机号码已存在").build();
        }
        //校验密码是否符合规则
        String firstPassword = user.getFirstPassword();
        boolean matches = Pattern.matches("^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?!.*?[*?!&￥$%^#,./@\";:><\\[\\]}{\\-=+_\\\\|》《。，、？’‘“”~ `]).{8,16}$", firstPassword);
        if(!matches){
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("密码不符合规则，请重新设置密码！").build();
        }
        String s1 = ShiroUtils.md5Salt(user.getFirstPassword(), user.getUsername() + ShiroUtils.SALT);
        if (user.getUseTime().equals("长期")){
            user.setEnabled(true).setStatus(0).setCreateTime(new Date()).setPassword(s1).setAccount("正常");
        }else {
            if (user.getStartTime().getTime()<new Date().getTime() && 86400000+user.getEndTime().getTime()>new Date().getTime()){
                user.setEnabled(true).setStatus(0).setCreateTime(new Date()).setPassword(s1).setAccount("正常");
            }else {
                user.setEnabled(true).setStatus(0).setCreateTime(new Date()).setPassword(s1).setAccount("已停用");
            }
        }

        int insert = sysUserDao.insert(user);

        if (insert > 0) {
            if (!StringUtil.isNullOrEmpty(sysUser.getString("role"))) {
                sysUserRoleDao.insert(new SysUserRole().setRoleId(sysUser.getString("role")).setUserId(user.getId()));
            }
            JSONArray communitys = sysUser.getJSONArray("communitys");
            List<String> list = communitys.toJavaList(String.class);
            for (String s : list) {
                sysUserCommunityDao.insert(new SysUserCommunity().setCommunityId(s).setUserId(user.getId()));
            }
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        } else {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult update(HttpServletRequest request,JSONObject sysUser) {
        User user = JSONObject.parseObject(sysUser.toJSONString(), User.class);
        String firstPassword = user.getFirstPassword();
        boolean matches = Pattern.matches("^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?!.*?[*?!&￥$%^#,./@\";:><\\[\\]}{\\-=+_\\\\|》《。，、？’‘“”~ `]).{8,16}$", firstPassword);
        if(!matches){
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("密码不符合规则，请重新设置密码！").build();
        }
//        用户名,手机号验重
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
//        queryWrapper.eq("enabled",true);
        User user2 = sysUserDao.selectOne(queryWrapper);
        if (Optional.ofNullable(user2).isPresent() && !user2.getId().equals(user.getId())) {
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("用户名已存在").build();
        }

        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("tel", user.getTel());
//        queryWrapper2.eq("enabled",true);
        User user3 = sysUserDao.selectOne(queryWrapper2);
        if (Optional.ofNullable(user3).isPresent() && !user3.getId().equals(user.getId())) {
            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("手机号码已存在").build();
        }
//        if (user.getPassword().equals(user.getOldPassword())){//需要解密对比
//            return ResponseResult.builder().code(ResultCode.WRONG_REQUEST_PARAMETER.getCode()).message("密码重复").build();
//        }
        User user5 = sysUserDao.selectById(user.getId());
        //user5修改前
        //user 当前需要修改的
        SysRole role = sysRoleDao.findByUserId(user5.getId());


        Date startTime = user.getStartTime();
        Date endTime = user.getEndTime();
        if (user.getUseTime().equals("临时")) {
            long time = new Date().getTime();
            long time1 = endTime.getTime();
            time1 += 86400000;

            if (time < time1 && time > startTime.getTime()) {
                user.setAccount("正常");
            }else {
                user.setAccount("已停用");
            }
        }else{
            user.setAccount("正常").setStartTime(null).setEndTime(null);

        }
        int update = sysUserDao.updateById(user);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("账号信息");
        sysLog.setType("修改");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user4 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user4.getUsername());
        sysLog.setContent("用户名:"+user.getUsername());
        StringBuilder builder = new StringBuilder();
        if(!user5.getUsername().equals(user.getUsername())){
            builder.append("用户名被修改,修改前:").append(user5.getUsername()).append(",修改后:").append(user.getUsername()).append(".");
        }
        if(StringUtils.hasText(user5.getUseTime())){
            if(StringUtils.hasText(user.getUseTime())){
                if(!user5.getUseTime().equals(user.getUseTime())){
                    builder.append("账号类型被修改,修改前:").append(user5.getUseTime()).append(",修改后:").append(user.getUseTime()).append(".");
                }
            }else {
                builder.append("账号类型被修改,修改前:").append(user5.getUseTime()).append(",修改后:无").append(".");
            }
        }else {
            if(StringUtils.hasText(user.getUseTime())){
                builder.append("账号类型被修改,修改前:无").append(",修改后:").append(user.getUseTime()).append(".");
            }
        }
        if(!user5.getFirstPassword().equals(user.getFirstPassword())){
            builder.append("账号初始密码被修改,修改前:").append(user5.getFirstPassword()).append(",修改后:").append(user.getFirstPassword()).append(".");
        }
        if(!user5.getTel().equals(user.getTel())){
            builder.append("账号初始手机号被修改,修改前:").append(user5.getTel()).append(",修改后:").append(user.getTel()).append(".");
        }
        if(StringUtils.hasText(user5.getRemark())){
            if(StringUtils.hasText(user.getRemark())){
                if(!user5.getRemark().equals(user.getRemark())){
                    builder.append("账号初始备注被修改,修改前:").append(user5.getRemark()).append(",修改后:").append(user.getRemark()).append(".");
                }
            }else {
                builder.append("账号初始备注被修改,修改前:").append(user5.getRemark()).append(",修改后:无").append(".");
            }
        }else {
            if(StringUtils.hasText(user.getRemark())){
                builder.append("账号初始备注被修改,修改前:无").append(",修改后:").append(user.getRemark()).append(".");
            }
        }

        SysRole role1 = sysRoleDao.selectById(sysUser.getString("role"));
        if(role != null){
            if(role1 != null){
                if(!role.getName().equals(role1.getName())){
                    builder.append("账号角色名称被修改,修改前:").append(role.getName()).append(",修改后:").append(role1.getName()).append(".");
                }
            }
        }else {
            if(role1 != null){
                builder.append("账号角色名称被修改,修改前:无").append(",修改后:").append(role1.getName()).append(".");
            }
        }
        LambdaQueryWrapper<SysUserCommunity> queryWrapper11 = new LambdaQueryWrapper<>();
        queryWrapper11.eq(SysUserCommunity::getUserId,user5.getId());
        List<SysUserCommunity> sysUserCommunities1 = sysUserCommunityDao.selectList(queryWrapper11);
        if(sysUserCommunities1 != null && sysUserCommunities1.size()>0){
            LambdaQueryWrapper<SysCommunity> queryWrapper12 = new LambdaQueryWrapper<>();
            queryWrapper12.eq(SysCommunity::getEnable,true);
            queryWrapper12.in(SysCommunity::getId,sysUserCommunities1.stream().map(SysUserCommunity::getCommunityId).collect(Collectors.toList()));
            List<SysCommunity> sysCommunities = sysCommunityDao.selectList(queryWrapper12);
            List<String> communityNames = null;
            if(sysCommunities != null && sysCommunities.size()>0){
                communityNames = sysCommunities.stream().map(SysCommunity::getName).collect(Collectors.toList());
            }

            LambdaQueryWrapper<SysCommunity> queryWrapper13 = new LambdaQueryWrapper<>();
            List<String> communitys1 = sysUser.getJSONArray("communitys").toJavaList(String.class);
            if(communitys1 == null || communitys1.size()<=0){
                if(communityNames != null){
                    builder.append("账号社区权限修改,修改前:").append(communityNames).append(",修改后:无").append(".");
                }
            }else {
                if(communityNames == null){
                    builder.append("账号社区权限修改,修改前:无").append(",修改后:").append(communitys1).append(".");
                }else{
                    queryWrapper13.in(SysCommunity::getId,communitys1);
                    List<SysCommunity> sysCommunities1 = sysCommunityDao.selectList(queryWrapper13);
                    List<String> communityNames2 = sysCommunities1.stream().map(SysCommunity::getName).collect(Collectors.toList());
                    builder.append("账号社区权限修改,修改前:").append(communityNames).append(",修改后:").append(communityNames2).append(".");
                }

            }
        }else{
            List<String> communitys1 = sysUser.getJSONArray("communitys").toJavaList(String.class);
            if(communitys1 != null && communitys1.size()>0){
                LambdaQueryWrapper<SysCommunity> queryWrapper13 = new LambdaQueryWrapper<>();
                queryWrapper13.in(SysCommunity::getId,communitys1);
                List<SysCommunity> sysCommunities1 = sysCommunityDao.selectList(queryWrapper13);
                List<String> communityNames2 = sysCommunities1.stream().map(SysCommunity::getName).collect(Collectors.toList());
                builder.append("账号社区权限修改,修改前:无").append(",修改后:").append(communityNames2).append(".");
            }
        }




        sysLog.setDetails(builder.toString());

        if (update > 0) {
            sysLog.setResult("成功");
            sysLogDao.insert(sysLog);
            QueryWrapper<SysUserRole> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("user_id", sysUser.getString("id"));
            List<SysUserRole> sysUserRoles = sysUserRoleDao.selectList(queryWrapper3);
            for (SysUserRole sysUserRole : sysUserRoles) {
                sysUserRoleDao.deleteById(sysUserRole.getId());
            }

            QueryWrapper<SysUserCommunity> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("user_id", sysUser.getString("id"));
            List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(queryWrapper4);
            for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
                sysUserCommunityDao.deleteById(sysUserCommunity.getId());
            }


            User user1 = sysUserDao.selectById(sysUser.getString("id"));
            sysUserRoleDao.insert(new SysUserRole().setRoleId(sysUser.getString("role")).setUserId(sysUser.getString("id")));
            JSONArray communitys = sysUser.getJSONArray("communitys");
            List<String> list = communitys.toJavaList(String.class);
            for (String s : list) {
                sysUserCommunityDao.insert(new SysUserCommunity().setCommunityId(s).setUserId(sysUser.getString("id")));
            }
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        } else {
            sysLog.setResult("失败");
            sysLogDao.insert(sysLog);
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteById(HttpServletRequest request,String parseObject) {
        User user = sysUserDao.selectById(parseObject);
        user.setEnabled(false).setDeleteTime(new Date());
        int i = sysUserDao.updateById(user);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("账号信息");
        sysLog.setType("删除");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());
        sysLog.setIncident("用户名:"+user.getUsername());
        if (i > 0) {
            sysLog.setResult("成功");
            QueryWrapper<SysUserRole> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("user_id", parseObject);
            List<SysUserRole> sysUserRoles = sysUserRoleDao.selectList(queryWrapper3);
            for (SysUserRole sysUserRole : sysUserRoles) {
                sysUserRoleDao.deleteById(sysUserRole.getId());
            }

            QueryWrapper<SysUserCommunity> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("user_id", parseObject);
            List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(queryWrapper4);
            for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
                sysUserCommunityDao.deleteById(sysUserCommunity.getId());
            }
            int insert = sysLogDao.insert(sysLog);
            if(insert>0){
                log.info("删除账号日志记录成功");
            }else {
                log.error("删除账号日志记录失败");
            }
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        } else {
            sysLog.setResult("失败");
            int insert = sysLogDao.insert(sysLog);
            if(insert>0){
                log.info("删除账号日志记录成功");
            }else {
                log.error("删除账号日志记录失败");
            }
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
    }

    @Override
    public ResponseResult selectPage(Integer page, Integer limit, String condition, String useTime, String account) {
        Page<User> page1 = new Page<>(page, limit);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", true);
        queryWrapper.ne("username","admin");
        if (!StringUtils.isEmpty(condition))
            queryWrapper.and(userQueryWrapper -> userQueryWrapper.like(StringUtils.hasText(condition),"username", condition).or().like(StringUtils.hasText(condition),"tel", condition));
        if (Optional.ofNullable(useTime).isPresent() && !StringUtils.isEmpty(useTime)){
            queryWrapper.eq("use_time",useTime);
        }

        if (Optional.ofNullable(account).isPresent() && !StringUtils.isEmpty(account)){
            queryWrapper.eq("account",account);
        }
        Page<User> userPage = sysUserDao.selectPage(page1, queryWrapper);
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (User user : userPage.getRecords()){
            QueryWrapper<SysUserCommunity> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("user_id",user.getId());
            List<SysUserCommunity> sysRoleMenus = sysUserCommunityDao.selectList(queryWrapper1);

            QueryWrapper<SysUserRole> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("user_id",user.getId());
            SysUserRole sysUserRoles = sysUserRoleDao.selectOne(queryWrapper2);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(user));
            if (Optional.ofNullable(sysUserRoles).isPresent()){
                SysRole sysRole = sysRoleDao.selectById(sysUserRoles.getRoleId());
                if (Optional.ofNullable(sysRole).isPresent()){
                    jsonObject.put("role",sysRole.getName());
                    jsonObject.put("role_id",sysRole.getId());
                }else {
                    jsonObject.put("role",null);
                }
            }else {
                jsonObject.put("role",null);
            }

            List<JSONObject> list = new ArrayList<>();
            for (SysUserCommunity sysUserCommunity : sysRoleMenus){
                LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysCommunity::getId,sysUserCommunity.getCommunityId());
                lambdaQueryWrapper.eq(SysCommunity::getEnable,true);
                SysCommunity sysCommunity = sysCommunityDao.selectOne(lambdaQueryWrapper);
                //SysCommunity sysCommunity = sysCommunityDao.selectById(sysUserCommunity.getCommunityId());

                if (Optional.ofNullable(sysCommunity).isPresent()){
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("name",sysCommunity.getName());
                    jsonObject1.put("id",sysCommunity.getId());
                    list.add(jsonObject1);
                }
            }


            jsonObject.put("communitys",list);

            jsonObjects.add(jsonObject);
        }

        Page<JSONObject> page2 = new Page<>();
        page2.setPages(userPage.getPages());
        page2.setMaxLimit(userPage.getMaxLimit());
        page2.setRecords(jsonObjects);
        page2.setSize(userPage.getSize());
        page2.setCurrent(userPage.getCurrent());
        page2.setTotal(userPage.getTotal());
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).data(page2).build();
    }

    @Override
    public ResponseResult roleChages(HttpServletRequest request,JSONObject jsonObject) {
        JSONArray users = jsonObject.getJSONArray("users");
        String role = jsonObject.getString("role");
        List<String> list1 = users.toJavaList(String.class);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("账号信息");
        sysLog.setType("批量修改角色");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());
        StringBuilder stringBuilder = new StringBuilder("修改");
        stringBuilder.append(list1.size()).append("个用户角色为");
        SysRole sysRole = sysRoleDao.selectById(role);
        stringBuilder.append(sysRole.getName());
        sysLog.setContent(stringBuilder.toString());

        StringBuilder builder = new StringBuilder();
        builder.append("用户角色:批量修改为[").append(sysRole.getName()).append("]  |  用户名:");
        for (String s : list1) {
            User user = sysUserDao.selectById(s);
            builder.append(user.getUsername());
            if(list1.indexOf(s) != list1.size()-1){
                builder.append(",");
            }
        }
        sysLog.setDetails(builder.toString());
        for (String s : list1){
            QueryWrapper<SysUserRole> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("user_id",s);
            List<SysUserRole> sysUserRoles = sysUserRoleDao.selectList(queryWrapper3);
            for (SysUserRole sysUserRole : sysUserRoles){
                sysUserRoleDao.deleteById(sysUserRole.getId());
            }

            sysUserRoleDao.insert(new SysUserRole().setUserId(s).setRoleId(role));
        }
        sysLog.setResult("成功");
        int insert = sysLogDao.insert(sysLog);
        if(insert>0){
            log.info("批量修改角色日志记录成功");
        }else {
            log.error("批量修改角色日志记录失败");
        }
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
    }

    @Override
    public ResponseResult comChages(HttpServletRequest request,JSONObject jsonObject) {
        JSONArray users = jsonObject.getJSONArray("users");//用户id数组
        JSONArray com = jsonObject.getJSONArray("com");//社区id数组
//        String com = jsonObject.getString("com");
        List<String> list1 = users.toJavaList(String.class);
        List<String> list2 = com.toJavaList(String.class);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("账号信息");
        sysLog.setType("批量修改权限");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());
        StringBuilder builder = new StringBuilder();
        builder.append("用户权限批量修改为:[");
        sysLog.setDetails(builder.toString());
        StringBuilder stringBuilder = new StringBuilder("修改");
        stringBuilder.append(list1.size()).append("个用户权限为[");
        for (String s : list2) {
            SysCommunity sysCommunity = sysCommunityDao.selectById(s);
            stringBuilder.append(sysCommunity.getName());

            builder.append(sysCommunity.getName());
            if(list2.indexOf(s) != list2.size()-1){
                builder.append(",");
                stringBuilder.append(",");
            }

        }
        builder.append("]  | 用户名:");
        for (String s : list1) {
            User user = sysUserDao.selectById(s);
            builder.append(user.getUsername());
            if(list1.indexOf(s) != list1.size()-1){
                builder.append(",");
            }
        }
        stringBuilder.append("]");
        sysLog.setContent(stringBuilder.toString());
        sysLog.setDetails(builder.toString());
        for (String s : list1){
            QueryWrapper<SysUserCommunity> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("user_id",s);
            List<SysUserCommunity> sysUserRoles = sysUserCommunityDao.selectList(queryWrapper3);
            for (SysUserCommunity sysUserCommunity : sysUserRoles){
                sysUserCommunityDao.deleteById(sysUserCommunity.getId());
            }

            for (String s1 : list2) {
                sysUserCommunityDao.insert(new SysUserCommunity().setUserId(s).setCommunityId(s1));
            }
        }
        sysLog.setResult("成功");
        int insert = sysLogDao.insert(sysLog);
        if(insert>0){
            log.info("批量修改权限日志记录成功");
        }else {
            log.error("批量修改权限日志记录失败");
        }
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
    }
    
    @Override
    public ResponseResult deleteByIds(HttpServletRequest request,JSONObject jsonObject) {
        JSONArray ids = jsonObject.getJSONArray("ids");
        List<String> list = ids.toJavaList(String.class);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("账号信息");
        sysLog.setType("删除");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());

        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list){
            User user = sysUserDao.selectById(s);
            stringBuilder.append(user.getUsername()).append(" ");
            int i = sysUserDao.updateById(user.setEnabled(false).setDeleteTime(new Date()));

            if (i > 0) {
                QueryWrapper<SysUserRole> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("user_id", s);
                List<SysUserRole> sysUserRoles = sysUserRoleDao.selectList(queryWrapper3);
                for (SysUserRole sysUserRole : sysUserRoles) {
                    sysUserRoleDao.deleteById(sysUserRole.getId());
                }

                QueryWrapper<SysUserCommunity> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("user_id", s);
                List<SysUserCommunity> sysUserCommunities = sysUserCommunityDao.selectList(queryWrapper4);
                for (SysUserCommunity sysUserCommunity : sysUserCommunities) {
                    sysUserCommunityDao.deleteById(sysUserCommunity.getId());
                }
            } else {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("用户名:"+user.getUsername()+"发生错误").build();
            }
        }
        sysLog.setContent("用户名:"+stringBuilder);
        sysLog.setResult("成功");
        int insert = sysLogDao.insert(sysLog);
        if(insert>0){
            log.info("删除账号日志记录成功");
        }else {
            log.error("删除账号日志记录失败");
        }
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
    }

    @Override
    public ResponseResult reset(HttpServletRequest request,String id) {
        User user = sysUserDao.selectById(id);
        if (Optional.ofNullable(user).isPresent()){
            SysLog sysLog = new SysLog();
            sysLog.setIncident("账号信息");
            sysLog.setType("重置密码");
            sysLog.setValue("系统日志");
            sysLog.setCreateTime(new Date());
            sysLog.setIp(GetIp.getIpAddr(request));
            User user2 = (User) ShiroUtils.getSubject().getPrincipal();
            sysLog.setOperator(user2.getUsername());
            sysLog.setContent("用户名:"+user.getUsername());
            String s1 = ShiroUtils.md5Salt(user.getFirstPassword(), user.getUsername() + ShiroUtils.SALT);
            user.setPassword(s1);
            user.setModifyPasswordTime(null);
            int row = sysUserDao.updateById(user);
            sysUserDao.updateModifyPasswordTime(user.getId());
            if(row>0){
                sysLog.setResult("成功");
            }else {
                sysLog.setResult("失败");
            }
            int insert = sysLogDao.insert(sysLog);
            if(insert>0){
                log.info("日志记录重置密码成功！");
            }else {
                log.error("日志记录重置密码失败！");
            }
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        }else {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }

    }

    @Override
    public ResponseResult passwordchage(HttpServletRequest request,JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        String oldPassword = jsonObject.getString("oldPassword");
        String newPassword = jsonObject.getString("newPassword");
        //判断新密码是否符合系统的规则
        if(!checkPassWordRule(newPassword)){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("新密码不符合规则,请重新设置!").build();
        }
        User user = sysUserDao.selectById(id);
        SysLog sysLog = new SysLog();
        sysLog.setIncident("个人权限");
        sysLog.setType("修改密码");
        sysLog.setValue("系统日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());
        sysLog.setContent("用户修改个人登录密码");
        if (ShiroUtils.verifyPasswordSalt(oldPassword, user.getUsername() + ShiroUtils.SALT, user.getPassword())) {
            String s1 = ShiroUtils.md5Salt(newPassword, user.getUsername() + ShiroUtils.SALT);
            user.setPassword(s1);
            user.setModifyPasswordTime(new Date());//记录本次修改密码的时间
            int i = sysUserDao.updateById(user);
            if(i>0){
                redisUtil.deleteObject("popover:" + user2.getId());
                sysLog.setResult("成功");
            }else {
                sysLog.setResult("失败");
            }
            int insert = sysLogDao.insert(sysLog);
            if(insert>0){
               log.info("用户修改个人密码日志记录成功");
            }else {
                log.error("用户修改个人密码日志记录失败");
            }
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        }else{
            sysLog.setResult("失败");
            int insert = sysLogDao.insert(sysLog);
            if(insert>0){
                log.info("用户修改个人密码日志记录成功");
            }else {
                log.error("用户修改个人密码日志记录失败");
            }
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("旧密码错误").build();
        }
    }

    @Override
    public ResponseResult selectPage2(Integer page, Integer limit, String condition) {
        Page<User> page1 = new Page<>(page, limit);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", false);
        queryWrapper.ne("username","admin");
//        queryWrapper.or(userQueryWrapper -> userQueryWrapper.);
        if (!StringUtils.isEmpty(condition))
            queryWrapper.and(userQueryWrapper -> userQueryWrapper.like(StringUtils.hasText(condition),"username", condition).or().like(StringUtils.hasText(condition),"tel", condition));
        Page<User> userPage = sysUserDao.selectPage(page1, queryWrapper);
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (User user : userPage.getRecords()){
            QueryWrapper<SysUserCommunity> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("user_id",user.getId());
            List<SysUserCommunity> sysRoleMenus = sysUserCommunityDao.selectList(queryWrapper1);

            QueryWrapper<SysUserRole> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("user_id",user.getId());
            SysUserRole sysUserRoles = sysUserRoleDao.selectOne(queryWrapper2);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(user));
            if (Optional.ofNullable(sysUserRoles).isPresent()){
                SysRole sysRole = sysRoleDao.selectById(sysUserRoles.getRoleId());
                if (Optional.ofNullable(sysRole).isPresent()){
                    jsonObject.put("role",sysRole.getName());
                    jsonObject.put("role_id",sysRole.getId());
                }else {
                    jsonObject.put("role",null);
                }
            }else {
                jsonObject.put("role",null);
            }

            List<JSONObject> list = new ArrayList<>();
            for (SysUserCommunity sysUserCommunity : sysRoleMenus){
                LambdaQueryWrapper<SysCommunity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(SysCommunity::getId,sysUserCommunity.getCommunityId());
                lambdaQueryWrapper.eq(SysCommunity::getEnable,true);
                SysCommunity sysCommunity = sysCommunityDao.selectOne(lambdaQueryWrapper);
                //SysCommunity sysCommunity = sysCommunityDao.selectById(sysUserCommunity.getCommunityId());

                if (Optional.ofNullable(sysCommunity).isPresent()){
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("name",sysCommunity.getName());
                    jsonObject1.put("id",sysCommunity.getId());
                    list.add(jsonObject1);
                }
            }


            jsonObject.put("communitys",list);

            jsonObjects.add(jsonObject);
        }

        Page<JSONObject> page2 = new Page<>();
        page2.setPages(userPage.getPages());
        page2.setMaxLimit(userPage.getMaxLimit());
        page2.setRecords(jsonObjects);
        page2.setSize(userPage.getSize());
        page2.setCurrent(userPage.getCurrent());
        page2.setTotal(userPage.getTotal());
        return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).data(page2).build();
    }

    @Override
    public ResponseResult getBack(String id) {
        User user = sysUserDao.selectById(id);
        if (Optional.ofNullable(user).isPresent()){
            user.setEnabled(true);
            sysUserDao.updateById(user);
            return ResponseResult.builder().code(ResultCode.NORMAL.getCode()).message(ResultCode.NORMAL.getMessage()).build();
        }else {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
    }

    /**
     * 用户自己修改密码的规则判定
     */
    public boolean checkPassWordRule(String newPassword){
        //密码组合方式
        LambdaQueryWrapper<SysConfiguration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfiguration::getCode, Security.CHARACTER_COMBINATION.getCode());
        SysConfiguration sysConfiguration = sysConfigurationDao.selectOne(queryWrapper);
        String characterCombination = sysConfiguration.getValue();
        //开头，结尾，中间不可以有空格
        boolean matches1 = Pattern.matches("^[^\\s]*$",//
                newPassword);
        if(!matches1){
            return false;
        }
        //密码长度下限
        LambdaQueryWrapper<SysConfiguration> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(SysConfiguration::getCode, Security.PASSWORD_LOWER.getCode());
        SysConfiguration sysConfiguration2 = sysConfigurationDao.selectOne(queryWrapper2);
        String passwordLower = sysConfiguration2.getValue();
        int lowerLength = Integer.parseInt(passwordLower);

        //密码长度上限
        LambdaQueryWrapper<SysConfiguration> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(SysConfiguration::getCode, Security.PASSWORD_UPPER.getCode());
        SysConfiguration sysConfiguration3 = sysConfigurationDao.selectOne(queryWrapper3);
        String passwordUpper = sysConfiguration3.getValue();
        int upperLength = Integer.parseInt(passwordUpper);
//        boolean matches2 = Pattern.matches("^.{5,6}$",//
//                newPassword);
        if(newPassword.length() >= lowerLength && newPassword.length() <= upperLength){
            int count = 0;
            //[number,uppercase,lowercase,symbol]
            if(characterCombination.contains("number")){
                boolean matches = Pattern.matches(".*[0-9].*", newPassword);
                if(matches){
                    count+=1;
                }
            }
            if(characterCombination.contains("uppercase")){//大写字母
                boolean matches = Pattern.matches(".*[A-Z].*", newPassword);
                if(matches){
                    count+=1;
                }
            }
            if(characterCombination.contains("lowercase")){//小写字母
                boolean matches = Pattern.matches(".*[a-z].*", newPassword);
                if(matches){
                    count+=1;
                }
            }
            if(characterCombination.contains("symbol")){
                boolean matches = Pattern.matches(".*(?=.*\\d)(?=.*[a-zA-Z])(?=.*[`~!@#$%^&*()_\\-+=<>?:\"{}|,.;'·！￥…（）—《》？：“”【】、；‘，。])[\\da-zA-Z~!@#$%^&*.`()_\\-+=<>?:\"{}|,;'\\\\·！￥…（）—《》？：“”【】、；‘，。].*", newPassword);
                if(matches){
                    count+=1;
                }
            }
            return count>=3;
        }else {
            return false;
        }
    }

}
